import Cookies from "js-cookie";
import router from '../src/router/index'
import store from "./store";
import { getMenus } from "../src/api/init";
const getRoutes = () => {
    const id = Cookies.get('id')
    if (id) {
        return new Promise((resolve, reject) => {
            if (localStorage.getItem('menu')) {
                const userRoutes = JSON.parse(localStorage.getItem('menu'))
                const routes = handleAddRoute(userRoutes)
                store.dispatch('SET_ROUTES', routes)
                resolve(routes)
            } else {
                getMenus(id).then((res) => {
                    const userRoutes = res.data.data
                    localStorage.setItem('menu', JSON.stringify(userRoutes))

                    const routes = handleAddRoute(userRoutes)
                    store.dispatch('SET_ROUTES', routes)
                    resolve(routes)
                }).catch((err) => { console.log(err); })
            }

        })
    }

}
//处理路由数据格式
function handleAddRoute(asyncRoutes) {
    return asyncRoutes.map((item) => {
        console.log(item);
        const route = {
            path: item.path,
            name: item.name,
            // component: require(`@/views${item.component}/index.vue`)//不能这么写
            component: () => import(`@/views${item.component}/index.vue`)
        }

        return route
    })
}
const witeList = ['/login', '/admin']
router.beforeEach((to, from, next) => {
    const token = Cookies.get('token')
    if (token) {
        if (to.path == '/login') {
            next('/')
        } else if (to.path != '/login') {
            if (store.state.asyncRoutes.length == 0) {
                getRoutes().then(routes => {
                    if (routes.length > 0) {
                        routes.forEach((route) => {
                            router.addRoute('layout1', route)
                        })
                        next(to.path)
                    }
                })

            } else {
                if (to.matched.length != 0) {
                    next()
                } else {
                    alert('无权限')
                    next(from.path)
                }
            }
        }

    } else {
        if (witeList.indexOf(to.path) != -1) {
            next()
        } else {
            next(`/login?redirect=${to.path}`)
        }
    }
    next()
})